package com.promise.jokerdream.network

import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.IOException
import java.util.concurrent.TimeUnit

/**
 * 基于OkHttp的HTTP请求实现类
 */
class OkHttpApi : HttpApi {
    
    private val client: OkHttpClient by lazy {
        OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .build()
    }
    
    override fun get(url: String, headers: Map<String, String>?, callback: IHttpCallback) {
        val requestBuilder = Request.Builder().url(url)
        
        // 添加请求头
        headers?.forEach { (key, value) ->
            requestBuilder.addHeader(key, value)
        }
        
        val request = requestBuilder.build()
        executeRequest(request, callback)
    }
    
    
    /**
     * 执行HTTP请求
     */
    private fun executeRequest(request: Request, callback: IHttpCallback) {
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                callback.onFailure(call, e)
            }
            
            override fun onResponse(call: Call, response: Response) {
                callback.onSuccess(call, response)
            }
        })
    }
}